<template>
  <div>
    <h2 style="text-align: center">发布新课程</h2>
    <el-steps align-center :active="2" process-status="wait" style="margin-bottom: 40px;">
      <el-step title="填写课程基本信息"></el-step>
      <el-step title="创建课程大纲"></el-step>
      <el-step title="提交审核"></el-step>
    </el-steps>
    <!--表单，遍历课程目录-->
    <el-form label-width="120px">
      <el-form-item>
        <el-button type="text" @click="chapterDialogShow">添加章节</el-button>
        <!--章节-->
        <ul class="chanpterList">
          <li v-for="chap in chapterList" :ket="chap.id">
            <p>
              {{ chap.title }}
              <!--按钮-->
              <span class="acts">
                <el-button type="text" @click="ifVideo(chap.id)">添加课时</el-button>
                <el-button type="text" @click="chapterDialogShow(chap)">编辑</el-button>
                <el-button type="text" @click="deleteChapter(chap.id)">删除</el-button>
              </span>
            </p>
            <!--视频-->
            <ul class="chanpterList videoList">
              <li v-for="video in chap.children" :key="video.id">
                <p>
                  {{ video.title }}
                  <el-tag size="success" v-if="!video.videoSourceId">未上传视频</el-tag>
                  <!--按钮-->
                  <span class="acts">
                    <el-tag size="success" v-if="!video.free">免费</el-tag>
                    <el-button type="text" @click="findByIdVideo(video.id)">编辑</el-button>
                    <el-button type="text" @click="deleteVideo(video.id)">删除</el-button>
                  </span>
                </p>
              </li>
            </ul>
          </li>
        </ul>
      </el-form-item>
      <!--按钮-->
      <el-form-item>
        <el-button @click="$router.push({path: `/course/save/${courseId}`})">上一步</el-button>
        <el-button @click="$router.push({path: `/course/publish/${courseId}`})" type="primary">下一步</el-button>
      </el-form-item>
    </el-form>

    <!--文章：创建|修改的弹窗dialog-->
    <el-dialog :title="chapterDialogTitle" :visible.sync="chapterDialog">
      <el-form :model="chapter">
        <el-form-item label="章节标题">
          <el-input v-model="chapter.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number :min="0" v-model="chapter.sort"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="chapterDialog = false">取 消</el-button>
        <el-button type="primary" @click="addChapter">确 定</el-button>
      </div>
    </el-dialog>
    <!--课时：创建|修改的弹窗dialog-->
    <el-dialog :title="videoDialogTitle" @close="newRe" :visible.sync="dialogVideoFormVisible">
      <el-form :model="chapter">
        <el-form-item label="课时标题">
          <el-input v-model="video.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number :min="0" v-model="video.sort"/>
        </el-form-item>
        <el-form-item label="是否免费">
          <el-radio v-model="video.isFree" :label="0">免费</el-radio>
          <el-radio v-model="video.isFree" :label="1">默认</el-radio>
        </el-form-item>
        <el-form-item label="上传视频">
          <el-upload
            class="upload-demo"
            ref="upload"
            :action="uploadUrl"
            :on-progress="HandlerProgress"
            :on-success="handleSuccess"
            :on-remove="handleRemove"
            :on-error="handleError"
            :on-exceed="handleSurpass"
            :file-list="fileList"
            :limit="1"
            :auto-upload="false">
            <el-button slot="trigger" size="small" type="primary">选择视频</el-button>
            <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="newRe">取 消</el-button>
        <el-button type="primary" @click="saveVideo" :disabled="uploadBtn">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  createChapter,
  updateChapter,
  deleteChapter,
  findChapterById,
  findChapterOneById
} from '../../api/chapter/chapter'
import {createVideo, updateVideo, findByIdVideo, deleteVideo} from '../../api/video/video'
import {deleteVideoResource} from '../../api/vod/vod'

export default {
  name: "info",
  data() {
    return {
      // 课程id
      courseId: null,
      // 章节
      chapter: {
        id: null,
        title: '',
        sort: 0,
        courseId: null,
      },
      chapterList: [],
      // 弹窗
      chapterDialog: false,
      // 章节：弹窗表单提示信息
      chapterDialogTitle: '增加章节',
      // 课时：弹窗表单提示信息
      videoDialogTitle: '增加课时',
      // 课时按钮是否禁用
      saveVideoBtnDisabled: false,
      // 是否显示课时表单
      dialogVideoFormVisible: false,
      // 课时所在的章节id
      chapterId: '',
      // 课时对象
      video: {
        // id
        id: null,
        // 标题
        title: '',
        sort: 0,
        // 0免费，1默认
        isFree: 1,
        // 视频
        videoSourceId: '',
        // 视频标题
        videoTitle: '',
        // 章节id
        chapterId: null,
        // 课程id
        courseId: null,
        // 创建课时还是修改课时 0:创建,1:修改
        ifVideoOperation: 0
      },
      // 上传视频的文件信息
      fileList: [],
      // 上传视频的地址
      uploadUrl: 'http://localhost:9999/vod/upload',
      // 上传视频改变提交表单的按钮
      uploadBtn: false
    }
  },
  created() {
    // 获取路由的参数
    if (this.$route.params || this.$route.params.id) {
      // 获取创建的课程id
      this.courseId = this.$route.params.id
      this.chapter.courseId = this.$route.params.id
    }
    // 查询这个课程所有的章节
    this.findChapterById()
  },
  methods: {
    // *************************章节管理*****************************
    // 添加章节
    async createChapter() {
      let result = await createChapter(this.chapter)
      if (result.code === 20000) {
        this.$message.success('创建章节成功！')
        this.chapterDialog = false
        return false
      }
      this.$message.error('创建章节失败，' + result.data)
    },
    // 修改章节
    async updateChapter() {
      let result = await updateChapter(this.chapter)
      if (result.code === 20000) {
        this.$message.success('修改章节成功！')
        this.chapterDialog = false
        return false
      }
      this.$message.error('修改章节失败，' + result.data)
    },
    // 删除章节
    async deleteChapter(id) {
      // 提示信息
      this.$confirm('确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 删除逻辑
        let result = await deleteChapter(id)
        if (result.code === 20000) {
          this.$message.success('删除章节成功！')
          // 刷新
          await this.findChapterById()
          this.chapterDialog = false
          return false
        }
        this.$message.error('删除章节失败，' + result.message)
      })


    },
    // 查询这个课程的所有章节
    async findChapterById() {
      let result = await findChapterById(this.courseId)
      this.chapterList = result.data
    },
    // 增加章节，还是修改章节
    async addChapter() {
      // 判断章节id是否存在，存在则修改，否则删除
      if (this.chapter.id) {
        // 修改
        await this.updateChapter()
      } else {
        // 创建
        await this.createChapter()
      }
      // 50毫秒后执行刷新功能
      return setTimeout(() => {
        this.findChapterById()
      }, 50)
    },
    // 修改数据回显，创建清空表单
    async chapterDialogShow(data) {
      this.chapterDialog = true
      // 判断是修改还是创建
      if (data.id) {
        this.chapterDialogTitle = '修改章节'
        // 数据回显
        let result = await findChapterOneById(data.id)
        if (result.code === 20000) {
          this.chapter = result.data
          return false
        }
        this.$message.error('加载内容失败，' + result.data)
      } else {
        // 清空表单
        this.chapter.id = ''
        this.chapter.sort = 0
        this.chapter.title = ''
      }

    },

    // *************************课时管理*****************************
    // 上传视频，移除文件时
    async handleRemove(file, fileList) {
      // 删除视频调用接口
      // let result = await deleteVideoResource(this.video.videoSourceId)
      let result = await deleteVideoResource(this.video.videoSourceId)
      // 删除视频
      if (result.code !== 20000) {
        this.$message.warning('删除视频文件时发生意外！')
        return false
      }
      // 删除视频信息
      this.video.videoSourceId = ''
      this.video.videoTitle = ''
      // 清空数据中的信息
      let video = {
        id: this.video.id,
        videoSourceId: '',
        videoTitle: ''
      }
      let result2 = await updateVideo(video)
      if (result2.code !== 20000) {
        this.$message.warning('更新删除视频文件时发生意外！')
        return false
      }
    },
    // 上传成功
    handleSuccess(file, fileList) {
      this.$message.success("上传成功！")
      this.uploadBtn = false
      // 获取视频id
      this.video.videoSourceId = file.data
      console.log(fileList)
      // 获取视频标题
      this.video.videoTitle = fileList.name
    },
    // 上传失败
    handleError() {
      this.$message.error("文件上传失败，请重试！")
      this.uploadBtn = false
    },
    // 上传中
    HandlerProgress() {
      this.uploadBtn = true
    },
    // 文件超出个数限制时的钩子
    handleSurpass() {
      this.$message.warning("只能上传一个文件，更换文件请先删除当前文件")
    },
    // 开始上传视频
    submitUpload() {
      // 提交请求
      this.$refs.upload.submit()
    },
    // 增加前弹窗
    ifVideo(id) {
      // 显示弹窗
      this.dialogVideoFormVisible = true
      // 课程id
      this.video.courseId = this.courseId
      // 章节id
      this.video.chapterId = id
      // 创建操作
      this.ifVideoOperation = 0
    },
    // 修改前的弹窗
    async findByIdVideo(id) {
      // 修改操作
      this.ifVideoOperation = 1
      // 显示弹窗
      this.dialogVideoFormVisible = true
      // 调用接口
      let result = await findByIdVideo(id)
      if (result.code === 20000) {
        // 回显
        this.video = result.data
        // 判断这个课时是否存在视频资源
        if (this.video.videoSourceId) {
          this.fileList = [{name: this.video.videoTitle}]
        }
        return false
      }
      this.$message.error('课时加载失败，' + result.data)
    },
    // 修改课时
    async updateVideo() {
      let result = await updateVideo(this.video)
      if (result.code === 20000) {
        this.$message.success('修改课时成功！')
        // 关闭弹窗并刷新
        this.dialogVideoFormVisible = false
        await this.newRe()
        return false
      }
      this.$message.error('修改课时失败，' + result.data)
    },
    // 创建课时
    async createVideo() {
      let result = await createVideo(this.video)
      if (result.code === 20000) {
        this.$message.success('创建课时成功！')
        // 关闭弹窗并刷新
        this.dialogVideoFormVisible = false
        await this.newRe()
        return false
      }
      this.$message.error('创建课时失败，' + result.data)
    },
    // 删除课时
    async deleteVideo(id) {
      // 提示信息
      this.$confirm('确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 删除逻辑
        let result = await deleteVideo(id)
        if (result.code === 20000) {
          this.$message.success('删除课时成功！')
          // 刷新
          await this.findChapterById()
          return false
        }
        this.$message.error('删除课时失败，' + result.data)
      })
    },
    // 保存课时（修改，创建）
    async saveVideo() {
      if (this.ifVideoOperation === 1 && this.video.id) {
        // 修改
        await this.updateVideo()
      } else {
        // 创建
        await this.createVideo()
      }
    },
    // 刷新
    async newRe() {
      this.dialogVideoFormVisible = false
      await this.findChapterById()
      // 清空弹窗内容
      this.video.chapterId = null
      this.video.title = ''
      this.video.courseId = null
      this.video.free = 1
      this.video.videoSourceId = ''
      this.video.id = null
      this.video.sort = 0
      this.fileList = []
    }
  }
}
</script>

<style scoped lang="scss">
.chanpterList {
  position: relative;
  list-style: none;
  margin: 0;
  padding: 0;
}

.chanpterList li {
  position: relative;
}

.chanpterList p {
  float: left;
  font-size: 20px;
  margin: 10px 0;
  padding: 10px;
  height: 70px;
  line-height: 50px;
  width: 100%;
  border: 1px solid #DDD;
}

.chanpterList .acts {
  float: right;
  font-size: 14px;
}

.videoList {
  padding-left: 50px;
}

.videoList p {
  float: left;
  font-size: 14px;
  margin: 10px 0;
  padding: 10px;
  height: 50px;
  line-height: 30px;
  width: 100%;
  border: 1px dotted #DDD;
}

</style>
